package one.stand.config;

import lombok.extern.slf4j.Slf4j;
import one.stand.entity.WxNoticeEntity;
import one.stand.enums.*;
import one.stand.mapper.AppointmentMapper;
import one.stand.mapper.AssembleMapper;
import one.stand.mapper.OrdersMapper;
import one.stand.mapper.RefundRecordMapper;
import one.stand.model.*;
import one.stand.service.BaseService;
import one.stand.service.OrdersService;
import one.stand.service.WxMessageService;
import one.stand.service.WxPayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

/**
 * 定时任务
 *
 * @author: ZRH
 * @CreateDate: 2019/6/17 15:26
 */
@Slf4j
@Component
@EnableScheduling
public class ScheduledTask extends BaseService {



    @Scheduled(cron="0 0 0/1 * * ?")
    public void hourImplement() {
        log.info("每小时执行一次");
        // 修改订单状态 设置为已完成
        updateDeliveryTimeOrderState();
    }


    @Scheduled(cron="0 0/1 * * * ?")
    public void minuteImplement() {
        log.info("每分钟执行一次");

        // 修改订单状态 设置为已过期
        updateTimingOrderState();

        // 自动修改预约状态 设置为已过期
        updateTimingAppointmentState();

        // 拼团商品到期
        updateTimingAssembleState();
    }

    /**
     * 自动修改订单状态（设置为已完成）
     */
    @Async("asyncServiceExecutor")
    protected void updateDeliveryTimeOrderState(){
        ordersMapper.updateTimingUpdateOrderState(new OrdersModel(){{
            setOrderState(OrderStateEnum.BE_OVERDUE.getCode());
            setCreateTime(new Date());
        }});
    }

    /**
     * 自动修改订单状态（设置为已过期）
     */
    @Async("asyncServiceExecutor")
    protected void updateTimingOrderState(){
        ordersMapper.updateTimingUpdateOrderState(new OrdersModel(){{
            setOrderState(OrderStateEnum.BE_OVERDUE.getCode());
            setCreateTime(new Date());
        }});
    }

    /**
     * 自动修改预约状态（设置为已过期）
     */
    @Async("asyncServiceExecutor")
    protected void updateTimingAppointmentState(){
        AppointmentModel model = new AppointmentModel();
        model.setState(5);
        model.setStartTime(new Date());
        appointmentMapper.updateTimingAppointmentState(model);
    }

    /**
     * 拼团商品到期
     */
    @Async("asyncServiceExecutor")
    protected void updateTimingAssembleState(){
        AssembleModel model1 = new AssembleModel();
        model1.setAssembleTime(new Date());
        List<AssembleModel> list = assembleMapper.selectTimingAssembleState(model1);
        if(list == null || list.size() <= 0){
            return;
        }
        for(AssembleModel model : list){
            // 拼团未完成
            if(model.getAssembleNum() > model.getPutAssemble()){
                // 拼团失败
                updateAssembleState(model.getAssembleId(), 3);
                backRefundTwo(model.getAssembleId());
            }else{
            // 拼团已完成
                updateAssembleState(model.getAssembleId(), 2);
            }
        }
    }

    /**
     * 修改拼团状态
     * @param assembleId
     * @param state
     */
    private void updateAssembleState(Integer assembleId, Integer state){
        AssembleModel assembleModel = new AssembleModel();
        assembleModel.setState(state);
        assembleModel.setAssembleId(assembleId);
        assembleMapper.updateByPrimaryKeySelective(assembleModel);
    }

    @Autowired
    protected WxMessageService wxMessageService;

    @Autowired
    protected WxPayService wxPayService;

    /**
     * 微信退款
     */
    private void backRefundTwo(Integer assembleId) {
        if(assembleId == null){
            return;
        }
        // 查询退款订单
        List<OrdersModel> list = ordersMapper.selectAssemblePayment(assembleId);
        if(list == null || list.size() <= 0){
            return;
        }
        try {
            int ii = 0;
            for(OrdersModel model : list){
                String refundNo = getRefundNo();
                ResultModel resultModel = wxPayService.refund(model.getOutTradeNo(), refundNo, String.valueOf(model.getTotalFee()), String.valueOf(model.getPayPrice()), model.getRefundRemark(), model.getOrdersId());
                if(resultModel.isSuccess()){
                    // 修改订单状态
                    OrdersModel ordersModel = new OrdersModel();
                    ordersModel.setOrderState(OrderStateEnum.REFUND_SUCCESS.getCode());
                    ordersModel.setRefundState(RefundStateEnum.REFUND_SUCCESS.getCode());
                    ordersModel.setOrdersId(model.getOrdersId());
                    ordersMapper.updateByPrimaryKeySelective(ordersModel);
                    // 微信推送模板 订单状态改变消息
                    List<WxNoticeEntity> wxNoticeEntityList = ordersMapper.getSendTemplateInfo(new OrdersModel() {{
                        setType(2);
                        setOrdersId(model.getOrdersId());
                    }});
                    if(wxNoticeEntityList != null || wxNoticeEntityList.size() > 0){
                        WxNoticeEntity wxNoticeEntity1 = wxNoticeEntityList.get(0);
                        String[] fillData = {wxNoticeEntity1.getOrdersNo(), getLimitGoodsName(wxNoticeEntity1.getGoodsName()), money(model.getTotalFee()) + "元", OrderStateEnum.REFUND_SUCCESS.getMessage(), wxNoticeEntity1.getReceivePhone()};
                        wxMessageService.sendTemplate(wxNoticeEntity1.getUserOpenId(), wxNoticeEntity1.getUserFormId(), WxNoticeEnums.ORDER_STATE_USER.getCode(), fillData, LoginEnum.USER.getAccountType(),wxNoticeEntity1.getUserCompanyId());
                    }
                    // 添加退款记录信息
                    RefundRecordModel refundRecordModel = new RefundRecordModel();
                    refundRecordModel.setOrdersId(model.getOrdersId());
                    refundRecordModel.setOrdersNo(model.getOutTradeNo());
                    refundRecordModel.setRefundNo(refundNo);
                    refundRecordModel.setTotalFee(String.valueOf(model.getTotalFee()));
                    refundRecordModel.setRefundFee(String.valueOf(model.getTotalFee()));
                    refundRecordModel.setRefundStatus("SUCCESS");
                    refundRecordModel.setCreateTime(new Date());
                    refundRecordMapper.insertSelective(refundRecordModel);
                    ii++;
                }
            }
            if(list.size() == ii){
                // 全部退款成功
                updateAssembleState(assembleId, 4);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
